
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   db_util.py
@Time    :   2020/09/21 15:21:20
@Author  :   fengzhilaoling 
@Version :   1.0
@Contact :   fengzhilaoling@163.com
'''
import pymysql
class DBUtil:
    def __init__(self, user, pwd, host, db, port=3306):
        # 数据库连接对象
        self.client = pymysql.connect(
            user=user,
            password=pwd,
            host=host,
            port=port,
            database=db
        )
        # 游标对象
        self.cursor = self.client.cursor()
            
    def query(self, sql):
        # 调用原生SQL
        self.cursor.execute(sql)
        result = self.fetch_all_to_dict(self.cursor)
        return result


    def fetch_all_to_dict(self, cursor):
        desc = [i[0] for i in cursor.description]
        result = [dict(zip(desc, col)) for col in cursor.fetchall()]
        return result

    
    def add(self, sql):
        result = self.cursor.execute(sql)
        self.client.commit
        return result

    def update(self, sql):
        result = self.cursor.execute(sql)
        self.client.commit
        return result

    
    def delete(self, sql):
        result = self.cursor.execute(sql)
        self.client.commit
        return result

